#include "textediteventhandler.hpp"

TextEditEventHandler::TextEditEventHandler(QObject *parent) :
    QObject(parent)
{
    this->singleClickTimer = new QTimer();
    this->singleClickTimer->setSingleShot(true);
    this->singleClickTimer->setInterval(140);
    this->singleClickTimer->setProperty("endPoint", QPoint());
    connect(this->singleClickTimer, SIGNAL(timeout()), this, SLOT(onSingleClick()));

    this->mouseReleased = true;
}

bool TextEditEventHandler::eventFilter(QObject *obj, QEvent *event)
{
    //Filter Mouse DoubleClick -> Breakpoints
    if (event->type() == QEvent::MouseButtonDblClick)
    {
	this->singleClickTimer->stop();
	QMouseEvent *mouseEvent = static_cast<QMouseEvent *>(event);
	emit requestBreakPoint(mouseEvent->pos());
	return true;

    //Filter Mouse Click (pressed)
    } else if (event->type() == QEvent::MouseButtonPress) {
	QMouseEvent *mouseEvent = static_cast<QMouseEvent *>(event);
	this->singleClickTimer->setProperty("startPoint", mouseEvent->pos());
	this->mouseReleased = false;
	this->singleClickTimer->start();
	return true;

    //Filter Mouse Click (released) -> highlight on single click
    } else if (event->type() == QEvent::MouseButtonRelease) {
	QMouseEvent *mouseEvent = static_cast<QMouseEvent *>(event);
	this->mouseReleased = true;
	this->singleClickTimer->setProperty("endPoint", mouseEvent->pos());
	return true;

    //Filter scrolling with mouse wheel
    } else if (event->type() == QEvent::Wheel){
	return true;
    }

    return QObject::eventFilter(obj, event);
}


void TextEditEventHandler::onSingleClick()
{
    QTimer *timer = static_cast<QTimer*>(QObject::sender());

    if (!this->mouseReleased)
    {
	timer->start();
	return;
    }

    QPoint startPoint = timer->property("startPoint").toPoint();
    QPoint endPoint = timer->property("endPoint").toPoint();

    if (endPoint.isNull())
	emit requestHighlightLine(startPoint, startPoint);
    else
	emit requestHighlightLine(startPoint, endPoint);

    timer->setProperty("endPoint", QPoint());
}
